<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2018/8/1
 * Time: 16:23
 */
namespace app\api\controller\other;

use app\api\controller\BasicApi;
use app\api\service\MemberService;
use service\LogService;
use service\WechatService;
use think\Db;
use think\Exception;

class Pay extends BasicApi
{
    /**
     * 微信支付
     * @param $pay_log_id
     * @param $code
     * @return \think\response\Json
     */
    public function weixin($pay_log_id,$code)
    {
        try{
            $pay_log=Db::name('pay_log')->where('id',$pay_log_id)->find();
            sysconf('wechat_mch_id',config('wechat.mch_id'));
            sysconf('wechat_partnerkey',config('wechat.mch_key'));
            //获取OpenID
            $res=WechatService::WeMiniCrypt()->session($code);
            $openid=$res['openid'];
            $options['body']='广告团在线支付';
            $options['openid']=$openid;
            $options['out_trade_no']=$pay_log['order_sn'];
            $options['total_fee']=$pay_log['money']*100;
            //$options['total_fee']=1;
            $options['trade_type']='JSAPI';
            $options['notify_url']=request()->root(true).'/api/other.pay/weixin_notify_url';
            $order=WechatService::WeChatPay()->createOrder($options);
            /*
             * ["return_code"] => string(7) "SUCCESS"
              ["return_msg"] => string(2) "OK"
              ["appid"] => string(18) "wxc58a74bb2ea6ed78"
              ["mch_id"] => string(10) "1509168691"
              ["nonce_str"] => string(16) "BA0XNYW3GzjVJDC9"
              ["sign"] => string(32) "DAD935CFFE93F1BBB6BBCDA248552FA7"
              ["result_code"] => string(7) "SUCCESS"
              ["prepay_id"] => string(36) "wx01181859098719134bef49e41521566757"
              ["trade_type"] => string(5) "JSAPI"
             */
            $data=WechatService::WeChatPay()->createParamsForJsApi($order['prepay_id']);
            /**
             * ["appId"] => string(18) "wxc58a74bb2ea6ed78"
            ["timeStamp"] => string(10) "1533118884"
            ["nonceStr"] => string(32) "lzqydvq53t78pnkes2tul8bnd0gfwd79"
            ["package"] => string(46) "prepay_id=wx01182127542115deb8c780c60133021470"
            ["signType"] => string(3) "MD5"
            ["paySign"] => string(32) "8706445CC10A778E45288AEA7D427979"
            ["timestamp"] => string(10) "1533118884"
             */
            return json(['msg'=>'success','data'=>$data]);

        }catch (\Exception $e){
            return json(['msg'=>$e->getMessage()],500);
        }
    }

    /**
     * 微信支付回调
     * @return string
     */
    public function weixin_notify_url()
    {
        try{
            $data=WechatService::WeChatPay()->getNotify();
            if($data['return_code']=='SUCCESS'){
                $order_sn=$data['out_trade_no'];
                $data['total_fee']=$data['total_fee']/100;
                if($this->order_paid($order_sn,$data)){
                    return 'SUCCESS';
                }
            }
        }catch(\Exception $e){
            LogService::write('微信支付','微信支付回调异常：'.$e->getMessage().'['.$e->getCode().']');
        }
    }

    /**
     * 订单支付成功 业务逻辑处理
     * @param $order_sn
     * @param $data
     * @return bool
     */
    private function order_paid($order_sn,$data)
    {

        Db::startTrans();
        try{
            //查询这个支付记录
            $pay_log_db=Db::name('pay_log')->where('order_sn',$order_sn)->where('pay_status',0);
            $pay_log=$pay_log_db->find();
            //验证支付金额
            //if(!$pay_log||$pay_log['money']!=$data['total_fee'])return false;
            //修改支付记录为已付款
            Db::name('pay_log')->where('order_sn',$order_sn)->where('pay_status',0)->setField('pay_status', 1);
            //查询这个订单
            switch($pay_log['type']){
                case ORDER_TYPE_ADMISSION:
                    //入驻订单
                    $member_admission_db=Db::name(ORDER_TYPE_ADMISSION_ORDER_TABLE)->where('id',$pay_log['order_id']);
                    $order=$member_admission_db->find();
                    //修改支付时间
                    Db::name(ORDER_TYPE_ADMISSION_ORDER_TABLE)->where('id',$pay_log['order_id'])->setField('pay_time', time());
                    //修改到期时间
                    if($order['type']==USER_TYPE_WORKER){
                        //工人邦入驻
                        Db::name('worker_info')->where('mid',$order['mid'])
                            ->update([
                                'expiry_time'=>Db::raw('UNIX_TIMESTAMP(timestampadd(MONTH, '.$order['month'].', from_unixtime(expiry_time))) '),
                                'grade_id'=>$order['grade_id']
                            ]);
                    }elseif($order['type']==USER_TYPE_SUPPLIER){
                        //供应商入驻
                        Db::name('supplier_info')->where('mid',$order['mid'])
                            ->update([
                                'expiry_time'=> Db::raw('UNIX_TIMESTAMP(timestampadd(MONTH, '.$order['month'].', from_unixtime(expiry_time)))'),
                                'grade_id'=>$order['grade_id']
                            ]);
                    }
                    MemberService::rebate($order['mid'],$pay_log['money'],'推荐用户['.$order['mid'].']产生消费，获得佣金。');
                    //$this->rake_back($order['mid'],$pay_log['money'],ORDER_TYPE_ADMISSION);
                    break;
                case ORDER_TYPE_RECHARGE:
                    //充值订单
                    //修改支付状态
                    Db::name(ORDER_TYPE_RECHARGE_ORDER_TABLE)->where('id',$pay_log['order_id'])->setField('pay_time',time());
                    //给该用户增加可用余额
                    $recharge=Db::name(ORDER_TYPE_RECHARGE_ORDER_TABLE)->where('id',$pay_log['order_id'])->find();
                    $res=log_account_change($recharge['mid'],$recharge['money'],0,
                        '您于['.date('Y/m/d H:i:s').']成功充值金额['.$recharge['money'].']元,获得积分：'.($recharge['money']).'。',1);
                    if(!$res){
                        throw new Exception('充值业务处理失败');
                    }
                    $res=MemberService::rebate($recharge['mid'],$pay_log['money'],'推荐用户['.$recharge['mid'].']产生消费，获得佣金。');
                    //file_put_contents('test.txt',serialize($res).PHP_EOL,FILE_APPEND);
                    //$this->rake_back($recharge['mid'],$pay_log['money'],ORDER_TYPE_RECHARGE);
                    break;
                case ORDER_TYPE_EARNEST:
                    //诚意金订单
                    //修改支付状态
                    Db::name(ORDER_TYPE_EARNEST_ORDER_TABLE)->where('id',$pay_log['order_id'])->setField('status', 1);
                    $mid=Db::name(ORDER_TYPE_EARNEST_ORDER_TABLE)->where('id',$pay_log['order_id'])->value('mid');
                    log_credit_change($mid,EARNEST_CREDIT,EARNEST,'缴纳保证金加信用积分');
                    break;
            }
        }catch(\Exception $e){
            Db::rollback();
            LogService::write('支付日志','订单编号：'.$order_sn.'支付成功,业务逻辑处理失败,异常信息：'.$e->getMessage());
            return false;
        }
        Db::commit();
        return true;
    }

    /**
     * 推荐返佣
     * 弃用
     * @author jungshen
     */
    private function rake_back($mid,$money,$order_type){
        $parent=Db::name('store_member')->where('id',$mid)->field('id,parent_id')->find();
        if(!sysconf('rebate_obj'))return false;
        $rabate=explode('|',sysconf('rebate_obj'));
        $num=count($rabate);
        for ($i=0;$i<$num;$i++){
            if($parent['parent_id']>0){
                log_account_change($parent['parent_id'],$money*$rabate[$i],0,'推荐用户['.$mid.']产生消费，成功获得佣金['.($money*$rabate[$i]).']元。',2);
                $parent=Db::name('store_member')->where('id',$parent['parent_id'])->field('id,parent_id')->find();
            }else{
                break;
            }
        }
    }
}